<?php

class Coupons extends Admin_Controller {	
	
	var $coupon_id;
	
	function __construct()
	{		
		parent::__construct();
        
		$this->auth->check_access('Admin', true);
		$this->load->model('Coupon_model');
		$this->load->model('Product_model');
		$this->lang->load('coupon');
	}
	
	function index()
	{
		$data['page_title']	= lang('coupons');
		$data['coupons']	= $this->Coupon_model->get_coupons();
		
		$this->view($this->config->item('admin_folder').'/coupons', $data);
	}
	
	function add_from_list_coupon(){		
		
		$list = '["8IFGC6MQ","T8XFGMWB","MWLK6ZPY","EC7N7YQE","WAEFCATF","UF2LAQNQ","1LTZU224","5IGAQYPA","YWSAP9CZ","9JHPHPT1","R6DAWYR4","8J4SLV11","EEIZF5AG","2ICL3IB7","WLAFBSV1","PG56WMPL","8SMKJVKS","7DJF2879","EXLG4GCS","J9JEIAS4","E2521H8Z","Q354DTG6","A5ADAZ7E","SWBJJT8G","Z61EWZA2","MP4N3A4Y","I7C5UFFX","DGHJX72P","X79L5CP1","X6F46L4M","65SSRQ2B","CVZEQH9T","83VPRKHU","KI6FLTH7","6YKB3W1K","P5W6UMTS","XTVNQPMJ","MR9LFW9L","JNRQRYDQ","EB6SDMSM","ZG9I4P74","2UPNMVEW","A8B1SW4Q","HCUAAJ4D","FYZ8UK4K","TTJL8PW3","FN968P7M","Z9VNJBSZ","9C4TXBEW","ZNRF7ES4","XZJ71DPE","T29W7YVG","FLLAFX34","IEC4IZ22","S7947XJ1","2Q217HBT","ZQHMAE46","FZBN8GNU","29BVRDSJ","M971LW52","XRQUISI5","PGN4BSPH","N7QJNNDX","LNQWD6C6","9MCX51BY","DTDFRZ32","P1J3YUC7","YYLMIBW5","YDCW55HN","E2GLL3UG","2QQGMWQC","P4WA1CV1","11PRH518","T5XNT2YR","TAARPTFC","S6JSX87R","GIGG8ZYP","K5RLDVHX","XQ8W4MJ9","93K57ZVC","AWK3CQ81","RZYECKDZ","F2IXWB11","4UYEUMYU","G63JUCW8","APJ4N6MW","B87U3VVM","BIRIU6E7","1AXVPUYA","7BINDM9P","KB9MMA46","W2WI9K8F","YA74X7D9","HSV4GYAD","79PAKLQJ","VGFE1UFJ","A6T7JG63","55KEW6NX","73HTVSPT","8RB56ZZI","YXS6IKBS","6CNLR9FC","KRP8JU2Y","YXLRN1XD","2K6ZWJVC","KG5NY8JM","CC9HKRSY","2Y99KW94","H3WQMFST","DFYLI23T","GS6N1JVV","IVAMUNYQ","AG1BR635","IA7EHRYU","Y4HPT8DM","DNPWHB27","HQIS8SRC","21S3TC8S","UA6KZS89","KBG1HUHJ","2UE43ASE","YLQNITUK","4D8DJ8FS","7VL1W9BS","ZUMCCM7D","9333L5V8","QBN1GI26","6A5VNIIW","BQ9FXVZ7","WFSE2D9S","Q5GJRP1F","IJ2MTN3V","ZH9EXZ6W","XNVKWF17","4TMYFRDK","8QB9BP1R","24M9AZPG","CRCM4E5H","VE78HP4K","BRYR8KCH","HMDY1ULX","5Q6KN8NN","ZU5EWH8H","SNZ5HD23","B1HJ5LW9","AKEEMYJQ","H6FFQ6P9","MGED515K","I9Z1M8KG","UBZ3YITM","DC5CWQJV","V56I5IKX","3EVDHPLI","RWYMNZFF","LF74F5SE","GNBIJXE6","1E4KQ32H","1EA3RCG4","9DLRDGDS","F3UDB7L9","CAQNCBTB","PQZE7JUM","96FANMD2","SDR5GC69","12QMBFZ1","QY3K2ML3","MVLPCPQ7","HI1RYD44","3N3HPFJK","53JM9KQD","DF6ZDLG7","LKN9V9FU","I7U7FAG2","W2EKTF9J","IW45TFJ4","3HPM525G","CKYSJ1RD","3WLES55K","17E6L41V","X94VSP8X","ITG91MEK","LL734QEI","WE33SNVH","5XVZS7NA","4YBLW5GM","I86MT61B","5G5UC341","QG1Z7LHI","2YKT5HVL","TPH3WI2Y","SEKI9DQE","PVJVYVNM","CU7WQQNF","G28DCQFI","S8D2JKPN","26GL419L","2L6VQUU5","H9BK7T7X","6XKF8L2T","SCQ9L27H","48JQ3UDP","WDRMERB8","WH5QAJST","VDDRIYI8","JQAFTQA6","PCLKYLTE","2X2VPCWP","CAE4SQ8T","D4E2XGKH","U7TDXBQG","J9DWI1DG","73TDFDAB","JDWHF39P","DXE39WYD","EG2TPK84","EQKHFWRN","4ISUAJAR","AIDMYCL6","NI4L81GM","1ARHUAKW","2I12IXPQ","KZP32PLU","AGJ96B21","ZP9DLJRZ","DEM656HJ","8CFDHW1D","BACSGH2A","BZ64RPCZ","36M55AN9","9KIKCZRT","NZI75JEF","25GQ9QAU","5S1YHA7T","NNYMJXW4","FJ3G7H4F","56486MLK","KARP855A","GMTJ5SEA","JZ1LLA8B","L35LFEB7","ENVACVFL","LH1D3HBB","2BBNEYP3","GVIV32DN","KXDRTH3T","68L2E3J8","XI1JKIJQ","PJBZ3KU1","5293PZ5V","2TKM4I72","7K3C5XS9","A3GZHYN9","33HBXDJU","CBX27V7P","TIHZ29EM","9HZU98UD","EY4EJLCN","1NMDN3K9","TCBICFDW","LSVLEDFC","3P4DIQHD","2VQJH6CN","72HX1HQ2","BX68WED8","6CG7VP2X","GZ7LP5HY","YL273EG2","FZTQTBPX","LU8XLKYE","8Y1JAYZ5","32ZDI7JX","WWU433EJ","E8CIQB9Q","ET8D8NV7","KDAEBW2P","QP8CQQG2","LHUZ8XXX","XIT2J954","GKYBHFWC","YC1GQ9XE","6LPC3FYZ","U5SL9QSW","QM131V5V","JV6G5MRM","4MYJBSDY","4L52C2SK","CKGQY6Q9","IAPCWXXQ","FIKMX16S","SYUDT964","CE999CPI","VKK423IQ","49JLX5CH","T7XJMCXJ","Q4GNXE2N","LRVQK3GK","6WXGA5V2","8AELUB3U","HN1YZCSN","PSI8GZSB","LEN61ZSI","198JF5K1","L4X4E5WJ","6PJLQRHX","FSSR5R3U","64GDDUG2","4F957TDB","1HYUDEJE","M2A8LDR2","PU22PFQY","ZLX2DD8Y","85QYEXZR","766KHUS4","LFZLEWDS","8PZTXTGH","UPVYSBTZ","56ESQ883","WWC2H8DF","VMFHU43V","T4EUJL14","F21VCG1W","J92CYFRZ","VG816A25","5EBKPRL3","5T1UBK6L","KH5JSIIE","95EEUCEA","VJK88RJY","7GEPPKQ6","ZKLLZHNP","ZQYPV95A","YK8Q4NVN","MY5EFFMM","SJGJKB6V","56WUB386","FH93DFKA","GC9ZI6XY","XENCI12X","MH7V4RQX","AANC13MS","MLRG1SK6","G592ULBU","INWSABKK","IYFG2L35","8QMTVAM8","DQ8LJ3YM","RRYKTQS4","4HKGF1WD","6QV14M27","N8J2MEYB","EPD8R1EH","3W4C7A4G","GLH5QWU1","BK9C4LCU","EI7R28DR","F713CFPG","6DH3QZ1Q","DSCIXP4A","S7D6Q9QW","5CAPVGMB","8ZUX3ZJA","RWTL5N9K","ISXFS7GW","8EX7RCY2","NILNTVGR","JVNIQHRR","M8VK7ZKS","QBYK14NN","HWQ9XLR3","QQVCN7MS","6J6LZN2J","J4DTNRQ5","N58QF8FA","9FG1ZSWP","1QUI68W7","SR5YPA6H","8A32AQGC","62FKP9JH","ATWBQN5Q","DAAY3PZQ","6ACAI3WB","FIR1SKJ6","WRCYMYQ4","CQTTUY7U","H6YD5BN5","4VHC9SXQ","WK5HY5QD","PZQKZ4ST","7XXC4FUU","54KI3VP5","A9CWM73I","E6Z7I5QN","9JB6HFEE","J71KAUUF","2TW6N5TI","I7NPE12E","P32W8ABV","B6VIVNCL","6ATC4XWE","Z4N3NSQ1","HG6HB1L7","H13CTD8N","NK5DWLD6","UW3BBFTI","PPNYTM9E","1RN16YHK","JST9368T","2KUFCY9V","9UJAN5BG","XCMKVF5D","TUV2MKGC","M41FQD34","7USIWIQF","8TY1XR52","FTBPJW3Q","LIIBHMA7","IQELIRI9","V6PCEZIK","FL48U32Z","YTF3MSU7","7HEKIVPY","WESI82A1","TBAMI5E5","PYQP6TT2","A4SFVU8I","BH9KF1FB","KVUXK255","S1D72P5S","QLI5LQ5Z","4H3I1UXH","PBS3ZU91","9XEJBHTE","IZMQQGFB","9BABYKTI","7M34SJQS","4PSTY5WV","Q957834I","S2V1B53F","3US1Y3KF","BDKXZMC8","AE1J3K5K","PNUK1LQ8","CWUSIITY","XWQXD26G","8E9RBXJJ","Z5713XQW","YU9FGTEC","WB9T5BDK","JAVUX6CD","MHWBJ64G","YN3ZRZEL","9L5JAGXJ","82VTWAI3","NPZID9VV","CD9DF2RR","YSF7THWE","AN8NAA2M","3TGKK7Z6","4XTNGZGR","2T3NPD85","Q6ZD15Z4","VSAI62IC","8DRTWSKM","IQ42Y6WR","JJ4Y5W9F","1MHB4REE","QP2UPG2E","DIHBLTZ9","RTLFLIXM","KD41GCNB","LWQRV1W2","L6AFMBFL","BXGSGZZP","HY2K6SA4","UYSIFG5K","7QFF1Q9U","9YQZQDEN","RFEZ85BS","HW87CRRY","65YBSZGX","JUC4BL7H","FS4BPCPB","HQ2QMXQ8","IEU2X51X","9KC2BQC7","G17HIFGR","VF85BZ3D","8K5NG6ZS","B8PWNQWR","V4NKQDK2","LZSEDWTD","CLS6C2BI","RQFLEKT8","M3HHB847","RFPJSQW9","TITJLUZ5","K4K8IB4J","TXQB9XZ9","9R1KLEE1","MB8S9H3L"]
';
		$list = json_decode($list);
		
		//print_r($list);exit;
		$save['start_date']				= '2014-12-24';
		$save['end_date']				= '2015-01-31';
		$save['max_uses']				= '1';
		$save['whole_order_coupon'] 	= '1';
		$save['max_product_instances'] 	= '';
		$save['reduction_target']		= 'price';
		$save['reduction_type']			= 'fixed';
		$save['reduction_amount']		= '100000';
		// save coupon
		foreach($list as $key=>$value){
			$save['code'] = $value;
			$promo_id = $this->Coupon_model->save($save);
		}
	}
	
	function form($id = false)
	{
		
		//die(print_r($_POST));

		$this->load->helper(array('form', 'date'));
		$this->load->library('form_validation');
		
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		
		$this->coupon_id	= $id;
		
		$data['page_title']		= lang('coupon_form');
		
		//default values are empty if the product is new
		$data['id']						= '';
		$data['code']					= '';
		$data['start_date']				= '';
		$data['whole_order_coupon']		= 0;
		$data['max_product_instances'] 	= '';
		$data['end_date']				= '';
		$data['max_uses']				= '';
		$data['reduction_target'] 		= '';
		$data['reduction_type']			= '';
		$data['reduction_amount']		= '';
		$data['limit_price_cart']		= 0;
		
		$added = array();
		
		if ($id){	
			$coupon		= $this->Coupon_model->get_coupon($id);
			//if the product does not exist, redirect them to the product list with an error
			if (!$coupon)
			{
				$this->session->set_flashdata('message', lang('error_not_found'));
				redirect($this->config->item('admin_folder').'/product');
			}
				//set values to db values
			$data['id']						= $coupon->id;
			$data['code']					= $coupon->code;
			$data['start_date']				= $coupon->start_date;
			$data['end_date']				= $coupon->end_date;
			$data['whole_order_coupon']		= $coupon->whole_order_coupon;
			$data['max_product_instances'] 	= $coupon->max_product_instances;
			$data['num_uses']     			= $coupon->num_uses;
			$data['max_uses']				= $coupon->max_uses;
			$data['reduction_target']		= $coupon->reduction_target;
			$data['reduction_type']			= $coupon->reduction_type;
			$data['reduction_amount']		= $coupon->reduction_amount;
			$data['limit_price_cart']		= $coupon->limit_price_cart;
			
			$added = $this->Coupon_model->get_product_ids($id);
		}
		
		$this->form_validation->set_rules('code', 'lang:code', 'trim|required|callback_check_code');
		$this->form_validation->set_rules('max_uses', 'lang:max_uses', 'trim|numeric');
		$this->form_validation->set_rules('max_product_instances', 'lang:limit_per_order', 'trim|numeric');
		$this->form_validation->set_rules('whole_order_coupon', 'lang:whole_order_discount');
		$this->form_validation->set_rules('reduction_target', 'lang:reduction_target', 'trim|required');
		$this->form_validation->set_rules('reduction_type', 'lang:reduction_type', 'trim');
		$this->form_validation->set_rules('reduction_amount', 'lang:reduction_amount', 'trim|numeric');
		$this->form_validation->set_rules('start_date', 'lang:start_date');
		$this->form_validation->set_rules('end_date', 'lang:end_date');
		
		// create product list
		$products = $this->Product_model->get_products();
		
		// set up a 2x2 row list for now
		$data['product_rows'] = "";
		$x=0;
		while(TRUE) { // Yes, forever, until we find the end of our list
			if ( !isset($products[$x] )) break; // stop if we get to the end of our list
			$checked = "";
			if(in_array($products[$x]->id, $added))
			{
				$checked = "checked='checked'";
			}
			$data['product_rows']  .=  "<tr><td><input type='checkbox' name='product[]' value='". $products[$x]->id ."' $checked></td><td> ". $products[$x]->name ."</td>";
			
			$x++;
			
			//reset the checked value to nothing
			$checked = "";
			if ( isset($products[$x] )) { // if we've gotten to the end on this row
				if(in_array($products[$x]->id, $added))
				{
					$checked = "checked='checked'";
				}
				$data['product_rows']  .= 	"<td><input type='checkbox' name='product[]' value='". $products[$x]->id ."' $checked><td><td> ". $products[$x]->name ."</td></tr>";
			} else {
				$data['product_rows']  .= 	"<td> </td></tr>";
			}
			
			$x++;
		} 
		
	
		if ($this->form_validation->run() == FALSE)
		{
			$this->view($this->config->item('admin_folder').'/coupon_form', $data);
		}
		else
		{
			$save['id']						= $id;
			$save['code']					= $this->input->post('code');
			$save['start_date']				= $this->input->post('start_date');
			$save['end_date']				= $this->input->post('end_date');
			$save['max_uses']				= $this->input->post('max_uses');
			$save['whole_order_coupon'] 	= $this->input->post('whole_order_coupon');
			$save['max_product_instances'] 	= $this->input->post('max_product_instances');
			$save['reduction_target']		= $this->input->post('reduction_target');
			$save['reduction_type']			= $this->input->post('reduction_type');
			$save['reduction_amount']		= $this->input->post('reduction_amount');
			$save['limit_price_cart']		= $this->input->post('limit_price_cart');

			if($save['start_date']=='')
			{
				$save['start_date'] = null;
			}
			if($save['end_date']=='')
			{
				$save['end_date'] = null;
			}
			
			$product = $this->input->post('product');
			
			// save coupon
			$promo_id = $this->Coupon_model->save($save);
			//echo $this->db->last_query();exit;
			
			// save products if not a whole order coupon
			//   clear products first, then save again (the lazy way, but sequence is not utilized at the moment)
			$this->Coupon_model->remove_product($id);
			
			if(!$save['whole_order_coupon'] && $product) 
			{
				while(list(, $product_id) = each($product))
				{
					$this->Coupon_model->add_product($promo_id, $product_id);
				}
			}
			
			// We're done
			$this->session->set_flashdata('message', lang('message_saved_coupon'));
			
			//go back to the product list
			redirect($this->config->item('admin_folder').'/coupons');
		}
	}

	//this is a callback to make sure that 2 coupons don't have the same code
	function check_code($str)
	{
		$code = $this->Coupon_model->check_code($str, $this->coupon_id);
        if ($code)
       	{
			$this->form_validation->set_message('check_code', lang('error_already_used'));
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function delete($id = false)
	{
		if ($id)
		{	
			$coupon	= $this->Coupon_model->get_coupon($id);
			//if the promo does not exist, redirect them to the customer list with an error
			if (!$coupon)
			{
				$this->session->set_flashdata('error', lang('error_not_found'));
				redirect($this->config->item('admin_folder').'/coupons');
			}
			else
			{
				$this->Coupon_model->delete_coupon($id);
				
				$this->session->set_flashdata('message', lang('message_coupon_deleted'));
				redirect($this->config->item('admin_folder').'/coupons');
			}
		}
		else
		{
			//if they do not provide an id send them to the promo list page with an error
			$this->session->set_flashdata('message', lang('error_not_found'));
			redirect($this->config->item('admin_folder').'/coupons');
		}
	}
}